import { defineStore } from 'pinia'
import { reactive } from 'vue'
import {
  GET_TOKEN,
  SET_TOKEN,
  REMOVE_TOKEN,
  SET_EXPIRED,
  REMOVE_EXPIRED,
  GET_REFRESH_TOKEN,
  SET_REFRESH_TOKEN,
  REMOVE_REFRESH_TOKEN,
} from '@/utils/token'
import type { AdminLoginVo } from '@/api/acl/user/type'
import { loginUser } from '@/api/acl/user'
import { loginMenu } from '@/api/acl/menu'
import type { LeftMenuVo } from '@/api/acl/menu/type'
import { constantRoute, anyRoute } from '@/router/routes.ts'
import type { ApiResult, ApiUser } from '@/api/api.ts'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'

const modules: any = import.meta.glob('../../views/**/*.vue')
const Layout = () => import('@/layouts/index.vue')
function generateRoutes(menus: LeftMenuVo[]): RouteRecordRaw[] {
  const routers: RouteRecordRaw[] = []
  menus.forEach((item) => {
    const router: any = {
      name: item.name,
      meta: item.meta,
      path: item.path,
    }
    router.component =
      item.parentId === '0'
        ? Layout
        : modules[`../../views${item.path}/index.vue`]
    if (item.children) {
      router.children = generateRoutes(item.children)
    }
    routers.push(router)
  })
  return routers
}

const useUserStore: any = defineStore('user', (): any => {
  const userState = reactive<any>({
    accessToken: GET_TOKEN(),
    refreshToken: GET_REFRESH_TOKEN(),
    userInfo: null,
    menus: [] as RouteRecordRaw[],
  })

  // 缓存 accessToken
  const cacheAccessToken = async (result: AdminLoginVo) => {
    SET_TOKEN(result.tokenType + ' ' + result.accessToken)
    SET_EXPIRED(result.expiresIn)
    SET_REFRESH_TOKEN(result.refreshToken)
    userState.accessToken = result.accessToken
    userState.refreshToken = result.refreshToken
  }
  // 获取用户信息
  const getUserInfo = async () => {
    const currentUser: ApiResult<ApiUser> = await loginUser()
    userState.userInfo = currentUser.data
    //构建当前登录用户的菜单信息
    const result: ApiResult<LeftMenuVo[]> = await loginMenu()
    const routers: RouteRecordRaw[] = generateRoutes(result.data)
    userState.menus = [...constantRoute, ...routers, anyRoute]
    const syncRouters: RouteRecordRaw[] = [...routers, anyRoute]
    syncRouters.forEach((route: RouteRecordRaw) => {
      router.addRoute(route)
    })
  }

  // 退出登录
  const logout = () => {
    REMOVE_TOKEN()
    REMOVE_EXPIRED()
    REMOVE_REFRESH_TOKEN()
    userState.userInfo = null
    userState.accessToken = ''
    userState.refreshToken = ''
    userState.menus = []
    router.replace('/login').then(() => { })
  }
  return { userState, getUserInfo, cacheAccessToken, logout }
})

export default useUserStore
